﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SiteManager;
using System.Data.SqlClient;
using System.IO;
using System.Data;

public partial class Community_Presentation : System.Web.UI.Page
{
    Manager mgr = new Manager(true, "ConnectionString");
    protected void Page_Load(object sender, EventArgs e)
    {
      //  LoadPresentation();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtPresentaionTitle.Text))
        {

            lblMessage.Visible = true;
            lblMessage.Text = "Please enter Title";
            return;
        }
        Manager objManger = new Manager(true, "ConnectionString");
        int userType = 0;  //WILL USE TO SET ZERO(0) FOR DOCTOR AND 1 FOR DENTIST


        if (Session["userType"].ToString().Equals("Doctor", StringComparison.OrdinalIgnoreCase))
            userType = 2;
        //userType = 0; Change at 27/02/2008 because at pageresponse.aspx page  doctor usertype=2
        else if (Session["userType"].ToString().Equals("SiteUser", StringComparison.OrdinalIgnoreCase))
            userType = 3;
        else if (!string.IsNullOrEmpty(Session["userType"].ToString()) &&
            Session["userType"].ToString().Equals("Doctor", StringComparison.OrdinalIgnoreCase) &&
            !string.IsNullOrEmpty(Session["DoctorType"].ToString()) &&
            Session["DoctorType"].ToString().Equals("Dentist", StringComparison.OrdinalIgnoreCase))
            userType = 4;

        string strFileName = UploadFiles(uploadPic, "../PresentationThumbnail/");
        string strPresentationFileName = UploadFiles(uploadPresentation, "../Presentation/");
        SqlParameter[] objSqlParameter = new SqlParameter[8];
        objSqlParameter[0] = new SqlParameter("@Id", SqlDbType.BigInt);
        //objSqlParameter[0].Value = 0;
        if (btnSubmit.Text.ToUpper().Trim() == "Update".ToUpper().Trim())
        {
            objSqlParameter[0].Value = Convert.ToInt32(Session["EditID"].ToString());
        }
        else
        {
            objSqlParameter[0].Value = 0;
        }

        objSqlParameter[1] = new SqlParameter("@DoctorID", SqlDbType.BigInt);
        objSqlParameter[1].Value = Convert.ToInt32(Session["userID"]);
        objSqlParameter[2] = new SqlParameter("@DoctorType", SqlDbType.BigInt);
        objSqlParameter[2].Value = userType;
        objSqlParameter[3] = new SqlParameter("@Title", SqlDbType.VarChar);
        objSqlParameter[3].Value = txtPresentaionTitle.Text.ToString().Trim();
        objSqlParameter[4] = new SqlParameter("@ThumbNail", SqlDbType.VarChar);
        objSqlParameter[4].Value = !string.IsNullOrEmpty(strFileName) ? strFileName : string.Empty;
        objSqlParameter[5] = new SqlParameter("@PresentationFile", SqlDbType.VarChar);
        objSqlParameter[5].Value = !string.IsNullOrEmpty(strPresentationFileName) ? strPresentationFileName : string.Empty;

        objSqlParameter[6] = new SqlParameter("@IsAddOrUpdate", SqlDbType.Bit);
        objSqlParameter[6].Direction = ParameterDirection.Output;

        objSqlParameter[7] = new SqlParameter("@PostedOn", SqlDbType.DateTime);
        objSqlParameter[7].Value = System.DateTime.Now;

        objManger.ExecuteQuery("AddUpdatePresentaion", objSqlParameter);

        if (Convert.ToInt32(objSqlParameter[0].Value) == 0)
        {
            lblMessage.Visible = true;
            lblMessage.ForeColor = System.Drawing.Color.Green;

            lblMessage.Text = "Presentation Inserted successfully.";
            lblMessage.Font.Bold = true;
        }
        else
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Presentation Updated Successfully.";
            lblMessage.Font.Bold = true;
        }

        objManger = null;

        btnSubmit.Text = "Post";
      //  LoadPresentation();
    }

    private void LoadPresentation()
    {
        Manager mngr = new Manager(true, "ConnectionString");
        SqlDataReader objDataReader = null;
        objDataReader = mngr.ExecuteQuery("select * from tbl_Presentation where DoctorId=" + Convert.ToInt32(Session["userID"]));

        BindGrid(Convert.ToInt32(Session["userID"]));
        mngr = null;
    }

    private void BindGrid(int id)
    {
        //Filling the grid with the messages of the topic selected in the combo
        Manager objMgr = new Manager(true, "ConnectionString");
        string sql = "select ID,Title from tbl_Presentation where DoctorId=" + Convert.ToInt32(Session["userID"]) + "";
        DataSet ds = objMgr.ExecuteQuery(sql, "tbl_Presentation");
        if (ds.Tables[0].Rows.Count > 0)
        {
            grdMessages.DataSource = ds.Tables[0];
            //grdMessages.PageSize = Convert.ToInt32(Session["AdminPageSize"]);
            grdMessages.DataBind();
        }
        else
        {
            grdMessages.DataSource = ds.Tables[0];
            grdMessages.DataBind();
            lblMessage.Text = "No presentation exist for you!!";
            lblMessage.ForeColor = System.Drawing.Color.Red;
            return;

        }
        objMgr = null;
    }



    private string UploadFiles(FileUpload uploadPic, string FilePath)
    {
        string filename1 = string.Empty;
        if (uploadPic.HasFile && uploadPic.PostedFile != null && uploadPic.PostedFile.FileName != "")
        {
            string ImgPath1 = FilePath;
            filename1 = Path.GetFileName(uploadPic.PostedFile.FileName);
            string baseFile = Path.GetFileNameWithoutExtension(uploadPic.PostedFile.FileName);
            string extension = Path.GetExtension(uploadPic.PostedFile.FileName);
            int fileMatchCount = 1;
            // Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
            while (File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1))))
            {
                filename1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
                fileMatchCount++;
            }
            uploadPic.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1)));
        }
        return filename1;
    }


    protected void grdMessages_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdMessages.PageIndex = e.NewPageIndex;
        BindGrid(Convert.ToInt32(Session["userID"]));
    }

    // delete confirmation
    protected void grdMessages_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lnk = (LinkButton)e.Row.FindControl("lnkDelete");

                try
                {
                    string id = grdMessages.DataKeys[e.Row.RowIndex].Value.ToString();
                    lnk.Attributes.Add("onclick", "return confirm('Are you sure to delete this blog?')");
                }
                catch (Exception es)
                {
                    Response.Write(es.ToString());
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }

    // delete the topic
    protected void grdMessages_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            string id = grdMessages.DataKeys[e.RowIndex].Value.ToString();
            string delSql = "delete from tbl_Presentaion where doctorID=" + Convert.ToInt32(Session["userID"]) + " and id=" + id + "";
            mgr.ExecuteQuery(delSql);
            BindGrid(Convert.ToInt32(Session["userID"]));
            btnSubmit.Text = "Post";
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }

    protected void grdMessages_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.ToString().ToUpper().Trim() == "EditPresentation".ToUpper().Trim())
        {
            Manager objManager = new Manager(true, "ConnectionString");
            SqlDataReader objDataReader = null;
            string id = e.CommandArgument.ToString();
            Session["EditID"] = id;
            string editsql = "select * from tbl_Presentaion where doctorID=" + Convert.ToInt32(Session["userID"]) + " and id=" + id + "";
            objDataReader = objManager.ExecuteQuery(editsql);
            objDataReader.Read();
            if (objDataReader.HasRows)
            {
                txtPresentaionTitle.Text = objDataReader["Title"].ToString();
                lblMessage.Text = "";
                btnSubmit.Enabled = true;
                btnSubmit.Text = "Update";
            }
            objDataReader.Close();
            objManager = null;
        }
    }

}